package com.minhang.config.security.filter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.minhang.utils.encryption.RSAUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * json格式登录
 *
 * @author rookie
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {


    @Resource(name = "rsaKeyPair")
    private Map<String, Object> map;

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        //请求格式
        String methodPost = "POST";
        //判断是不是post请求
        if (!methodPost.equals(request.getMethod())) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        System.out.println(request.getContentType());
        //判断是不是json格式
        if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE)) {
            Map<String, String> loginData = new HashMap<>();
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                e.printStackTrace();
                throw new AuthenticationServiceException(e.getMessage());
            }
//            //获取加密后端数据
//            String data = loginData.get("data");
//            //提取关键数据
//            String content = easpString(data);
//            //解密
//            String body = RSAUtil.decryptDataOnJava(content, RSAUtil.getPrivateKey(map));
//            //获取数据
//            Map<String, String> map = (Map<String, String>) JSONObject.parse(body);
            String username = loginData.get(getUsernameParameter());
            String password = loginData.get(getPasswordParameter());
            username = username == null ? "" : username;
            password = password == null ? "" : password;
            username = username.trim();
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);
            setDetails(request, authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        return super.attemptAuthentication(request, response);
    }


    /**
     * 截取请求body的加密数据
     *
     * @param requestData
     * @return
     */
    public String easpString(String requestData) {
        if (requestData != null && !requestData.equals("")) {
            String s = "{\"requestData\":";
            if (!requestData.startsWith(s)) {
                throw new RuntimeException("参数【requestData】缺失异常！");
            } else {
                int closeLen = requestData.length() - 1;
                int openLen = "{\"requestData\":".length();
                return StringUtils.substring(requestData, openLen, closeLen);
            }
        }
        return "";
    }
}






